package oaSystem.web.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import oaSystem.biz.DepartmentBiz;
import oaSystem.biz.EmployeeBiz;
import oaSystem.biz.MessageAttachmentBiz;
import oaSystem.biz.MessageBiz;
import oaSystem.biz.MessageReceptionBiz;
import oaSystem.entity.Department;
import oaSystem.entity.Employee;
import oaSystem.entity.Message;
import oaSystem.entity.MessageAttachment;
import oaSystem.entity.MessageReception;
import oaSystem.web.security.Authorize;

@Controller
public class MessageController {
	@Autowired
	private MessageBiz messageBiz;
	@Autowired
	private MessageAttachmentBiz messageAttachmentBiz;
	@Autowired
	private MessageReceptionBiz messageReceptionBiz;
	@Autowired
	private EmployeeBiz employeeBiz;
	@Autowired
	private DepartmentBiz departmentBiz;
	/**
	 * 收件箱
	 * @return
	 */
	@Authorize(rules="message-inbox")
	@RequestMapping(value="/message-inbox",method=RequestMethod.GET)
	public String inbox(Map<String, Object> model,
			Integer pageNum,
			String search,
			HttpSession session ){
		searchEmail(model, pageNum,1, search, session);
		return "message";
	}
	
	/**
	 * 发件箱
	 * @param model
	 * @param pageNum
	 * @param search
	 * @param session
	 * @return
	 */
	@Authorize(rules="message-outbox")
	@RequestMapping(value="/message-outbox",method=RequestMethod.GET)
	public String outbox(Map<String, Object> model,
			Integer pageNum,
			String search,
			HttpSession session){
		searchEmail(model, pageNum,2, search, session);
		return "message";
	}
	/**
	 * 草稿箱
	 * @param model
	 * @param pageNum
	 * @param search
	 * @param session
	 * @return
	 */
	@Authorize(rules="message-draft")
	@RequestMapping(value="/message-draft",method=RequestMethod.GET)
	public String draf(Map<String, Object> model,
			Integer pageNum,
			String search,
			HttpSession session){
		searchEmail(model, pageNum,0, search, session);
		return "message";
	}
	/**
	 * 回收站
	 * @param model
	 * @param pageNum
	 * @param search
	 * @param session
	 * @return
	 */
	@Authorize(rules="message-rubbish")
	@RequestMapping(value="/message-rubbish",method=RequestMethod.GET)
	public String rubbish(Map<String, Object> model,
			Integer pageNum,
			String search,
			HttpSession session){
		searchEmail(model, pageNum,5, search, session);
		return "message";
	}
	
	/**
	 * 抽取方法（查询邮件 By categoryID）
	 * @param model
	 * @param pageNum
	 * @param categoryId
	 * @param search
	 * @param session
	 */
	private void searchEmail(Map<String, Object> model,
								Integer pageNum,
								Integer categoryId, 
								String search, 
								HttpSession session) {
		Employee employee = (Employee)session.getAttribute("user");
		Integer sessionId = employee.getId();//获得sessionId
		//分页
		int num=pageNum!=null?pageNum:1;
		int pageSize=5;
		categoryId=categoryId!=0?categoryId:0;
		int count=messageBiz.getMessageCount(sessionId,categoryId,search);
		int totalPage=count%pageSize==0?count/pageSize:count/pageSize+1;
		model.put("totalPage", totalPage);
		model.put("pageNum", num);
		model.put("categoryId", categoryId);
		List<Department> departmentList = departmentBiz.findAllDepartment();
		model.put("departmentList", departmentList);
		//获取邮件列表（收件箱，发件箱，草稿箱）
		model.put("MessageList", messageBiz.getMessageBySearch(sessionId,categoryId,num, pageSize,search));
	}
	
	/**
	 * 发邮件
	 * @param message
	 * @param session
	 * @param request
	 * @param isSend
	 * @return
	 */
	@Authorize(rules="message-send")
	@RequestMapping(value="/message",method=RequestMethod.POST)
	public String addMessage(Message message,
			HttpSession session,
			HttpServletRequest request,
			Integer isSend){
		//加入草稿箱
		//发送者添加到message里面
		Employee employee = (Employee)session.getAttribute("user");
		message.setCreator(employee);
		message.setSendTime(new Date());
		int level =Integer.parseInt(request.getParameter("importantId")); 
		message.setLevel(level);
		message.setStatus(0);
		message.setIsSent(false);
		
		List<Employee> receiverList = (List<Employee>) session.getAttribute("receiverList");
		StringBuilder receivers=new StringBuilder();
		for (Employee employee2 : receiverList) {
			Employee fetchEmp = employeeBiz.fetchEmployeeById(employee2.getId());
			receivers.append(fetchEmp.getName()+",");
		}
		String receiversStr = receivers.toString().substring(0, receivers.toString().lastIndexOf(","));
		message.setReceivers(receiversStr);
		//附件List
		//MessageAttachment ma =messageBiz.addMessageAttachment(messageAttachment);
		//添加草稿箱方法
		messageBiz.addMessageToDrafts(message,receiverList,null);
		//判断是否按了发送
		if(isSend==1){
			//修改message里面的发送状态
			messageBiz.sendMessage(message);
		}
		return "redirect:/message-inbox?parentId=40&categoryid=1";
	}
	
	/**
	 * 放入垃圾箱
	 * @param messageId
	 * @return
	 */
	@Authorize(rules="message-rubbish")
	@RequestMapping(value="/putIn-rubbish",method=RequestMethod.POST)
	public String putInrubbish(Integer messageId){
			if(messageReceptionBiz.fetchMessageReceptionByMessageId(messageId)!=null){
				List<MessageReception> MessageReceptionList = messageReceptionBiz.fetchMessageReceptionByMessageId(messageId);
				for (MessageReception messageReception : MessageReceptionList) {
					messageReception.setStatus(1);//0正常，1回收站，2删除
					messageReceptionBiz.updataMessageReception(messageReception);
				}
			}
			Message message = messageBiz.fetchMessageById(messageId);
			message.setStatus(1);
			messageBiz.updateMessage(message);
		return "redirect:/message-inbox?parentId=40&categoryid=1";
		
	}
	/**
	 * 删除邮件
	 * @param messageId
	 * @return
	 */
	@Authorize(rules="message-delete")
	@RequestMapping(value="/delete-message",method=RequestMethod.POST)
	public String deletemessage(Integer messageId){
			if(messageReceptionBiz.fetchMessageReceptionByMessageId(messageId)!=null){
				List<MessageReception> MessageReceptionList = messageReceptionBiz.fetchMessageReceptionByMessageId(messageId);
				for (MessageReception messageReception : MessageReceptionList) {
					messageReception.setStatus(2);//0正常，1回收站，2删除
					messageReceptionBiz.updataMessageReception(messageReception);
				}
			}
			if(messageAttachmentBiz.fetchMessageAttachmentMapperByMessageId(messageId)!=null){
				List<MessageAttachment> MessageAttachmentList = messageAttachmentBiz.fetchMessageAttachmentMapperByMessageId(messageId);
				for (MessageAttachment messageAttachment : MessageAttachmentList) {
					messageAttachmentBiz.deleteMessageAttachmentByMessageId(messageAttachment.getMessage().getId());
				}
			}
			Message message = messageBiz.fetchMessageById(messageId);
			message.setStatus(2);
			messageBiz.updateMessage(message);
		return "redirect:/message-inbox?parentId=40&categoryid=1";
	}
	
}
